package com.camin.android;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TableRow;

import com.camin.android.adapters.IngredientAdapter;
import com.camin.android.utils.Constants;

public class IngredientListActivity extends BaseActivity {

	private boolean showSearch = false;

	private ListView getListView()
	{
		return (ListView)findViewById(R.id.lvIngredients);
	}
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ingredient_list);

		refreshListItems();
		
		Button btnSearch = (Button) findViewById(R.id.btnSearchIngredient);
		btnSearch.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				showSearch = !showSearch;
				showSearchTextBox();
			}
		});
		
		Button btnAddIngredient = (Button) findViewById(R.id.btnAddIngredient);
		btnAddIngredient.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						IngredientActivity.class);
				startActivityForResult(intent, 0);

			}
		});

		
		getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				Intent data = new Intent();
				data.putExtra(Constants.INGREDIENT_ID, id);
				setResult(RESULT_OK, data);
				finish();
				
			}
		});		
		showSearchTextBox();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK)
		{
			refreshListItems();
	        
			Bundle extras = data.getExtras();
			if (extras != null) {
				long id = extras.getLong(Constants.INGREDIENT_ID, -1l);
				getListView().setSelection((int)id);
			}
	        
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void refreshListItems()
	{
		Cursor ingredientsCursor = getDataHelper().getAllIngredients(getDatabase());
		ingredientsCursor.moveToFirst();
		
		IngredientAdapter adapter = new IngredientAdapter(this, ingredientsCursor);
		getListView().setAdapter(adapter);	
		getDatabase().close();
	}
	
	private void showSearchTextBox() {
		TableRow trSearchIngredient = (TableRow) findViewById(R.id.trSearchIngredientRow);
		if (showSearch == true) {
			trSearchIngredient.setVisibility(View.VISIBLE);
		} else {
			trSearchIngredient.setVisibility(View.INVISIBLE);
		}
	}


}
